package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.dao.OverflowListDao;
import com.atguigu.jxc.dao.OverflowListGoodsDao;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.OverflowListGoodsService;
import com.atguigu.jxc.util.AuthContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OverflowListGoodsServiceImpl implements OverflowListGoodsService {

    @Autowired
    private OverflowListGoodsDao overflowListGoodsDao;

    @Autowired
    private OverflowListDao overflowListDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(OverflowList overflowList, String overflowListGoodsStr, HttpSession session) {
//     获取当前登录的用户名
//     根据用户名查询用户信息
       User userInfo = AuthContextHolder.getUserInfo(session);
       //保存报溢单overflowList
       overflowList.setUserId(userInfo.getUserId());
       overflowList.setTrueName(userInfo.getTrueName());
        overflowListDao.saveOverflowList(overflowList);
       //保存报溢单商品overflowListGoods
       //把字符串overflowListGoodsStr 转为对象 OverflowListGoods JSONObject.parseArray
       List<OverflowListGoods> damageListGoods = JSONObject.parseArray(overflowListGoodsStr, OverflowListGoods.class);
       damageListGoods.forEach(item -> {
           System.out.println(item);
           item.setOverflowListId(overflowList.getOverflowListId());
           overflowListGoodsDao.saveOverflowListGoods(item);
       });
    }

    //报溢单商品信息
    @Override
    public Map<String, Object> goodsList(Integer overflowListId) {
        List<OverflowListGoods> overflowListGoodsList=overflowListGoodsDao.goodsList(overflowListId);
        Map<String, Object> map=new HashMap<>();
        map.put("rows",overflowListGoodsList);
        return map;
    }
}
